"""
@file: user.py
@author: lingdubing
@time: 2024/11/19  16:04
@desc: 关于操作用户行为的路由
@character: utf-8
@contain: [check_username]
"""
from core.Auth import check_permission, get_id_by_token
from core.Utils import en_password
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Header
from models.models import User, UserRoleLink, Role
from schemas.response import *
from sqlmodel import Session, select
from database.mysql import engine
from schemas.login_model import RegisterModel
from database.redis import code_cache
from aioredis import Redis

router = APIRouter()


@router.get("/check", summary="检查用户是否注册过", response_model=ReturnNoneDataModel)
async def check_usr(username: str):
    """
    检查用户是否注册过
    :param username:
    :return:
    """
    with Session(engine) as session:
        stmt = select(User).where(User.username == username)
        user = session.exec(stmt).first()
        if user:
            return ReturnNoneDataModel(code=STATUS_CODE["success"], message="用户已注册", success=False)
        else:
            return ReturnNoneDataModel(code=STATUS_CODE["success"], message="用户未注册", success=True)


@router.post("/updatepsw", summary="更改用户密码", response_model=ReturnNoneDataModel)
async def update_usr(user: RegisterModel):
    """
    更改用户密码
    :return:
    """
    # 查询redis数据库里是否存在该用户名的验证码并验证
    cache: Redis = await code_cache()
    if not await cache.exists(user.username):
        return ReturnNoneDataModel(code=STATUS_CODE["method_not_allowed"], message="验证码已过期", success=True)
    redis_code = await cache.get(user.username)
    if redis_code != user.ver_code:
        return ReturnNoneDataModel(code=STATUS_CODE["method_not_allowed"], message="验证码错误", success=True)
    # 删除redis数据库里该用户名的验证码
    await cache.delete(user.username)
    # 查询数据库中是否存在该用户名
    with Session(engine) as session:
        user_info = session.exec(select(User).where(User.username == user.username)).first()
        if user_info:
            # 更新用户密码
            hashed_password = en_password(user.password)
            user_info.password = hashed_password
            session.add(user_info)
            session.commit()
            return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改密码成功", success=True)
        else:
            return ReturnNoneDataModel(code=STATUS_CODE["error"], message="该用户不存在", success=False)


@router.get('/userlist', summary="查询用户列表", dependencies=[Depends(check_permission)])
async def get_user_list(page: int, page_size: int, user_status: Optional[int] = None,
                        user_role_id: Optional[int] = None, user_id: Optional[str] = None):
    """
    查询用户列表
    :param user_id:
    :param user_role_id:
    :param user_status:
    :param page_size:
    :param page:
    :return:
    """

    offset = (page - 1) * page_size
    # 查询数据库中用户数据
    with Session(engine) as session:
        # 查询用户列表并应用分页
        user_list = []
        # 基础查询条件
        statement = select(User).offset(offset).limit(page_size)
        # 添加查询条件
        if user_status is not None:
            statement = statement.where(User.user_status == user_status)
        if user_role_id is not None:
            statement = statement.join(UserRoleLink, User.user_id == UserRoleLink.user_id).where(
                UserRoleLink.role_id == user_role_id)
        if user_id is not None:
            statement = statement.where(User.user_id == user_id)
        user_info = session.exec(statement).all()

        total = len(session.exec(select(User)).all())
        for val in user_info:
            # 查询用户的角色
            user_role = session.exec(select(UserRoleLink).where(UserRoleLink.user_id == val.user_id)).first()
            # 查询角色名称
            role = session.exec(select(Role).where(Role.role_id == user_role.role_id)).first()
            user_dict = {
                'create_time': val.create_time,
                'user_id': val.user_id,
                'username': val.username,
                'user_status': val.user_status,
                'role_name': role.role_name
            }
            user_list.append(user_dict)
        if total > 0:
            return ReturnDataModel(code=STATUS_CODE["success"], message="查询成功", success=True, data=user_list,
                                   total=total)
        else:
            return ReturnDataModel(code=STATUS_CODE["error"], message="没有用户数据", success=False, total=0, data=[])


@router.get('/update_user_status', summary='更改用户状态', response_model=ReturnNoneDataModel,
            dependencies=[Depends(check_permission)])
async def update_user_status(user_id: str):
    """
    更改用户状态
    :param user_id:
    :return:
    """
    with Session(engine) as session:
        statement = select(User).where(User.user_id == user_id)
        user_info = session.exec(statement).first()
        if user_info:
            if user_info.user_status == 1:
                user_info.user_status = 0
            else:
                user_info.user_status = 1
            session.add(user_info)
            session.commit()
            return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改状态成功", success=True)
        else:
            return ReturnNoneDataModel(code=STATUS_CODE["error"], message="该用户不存在", success=False)


@router.get('/update_user_role', summary='更改用户的角色', response_model=ReturnNoneDataModel,
            dependencies=[Depends(check_permission)])
async def update_user_role(role_id: str, user_id: str):
    """
    更改用户的角色
    :param role_id:
    :param user_id:
    :return:
    """

    with Session(engine) as session:
        statement = select(UserRoleLink).where(User.user_id == user_id)
        user_role_info = session.exec(statement).first()
        if user_role_info:
            user_role_info.role_id = role_id
            session.add(user_role_info)
            session.commit()
            return ReturnNoneDataModel(code=STATUS_CODE["success"], message="更改角色成功", success=True)
        else:
            return ReturnNoneDataModel(code=STATUS_CODE["error"], message="角色更改失败", success=False)


@router.get("/get_user_id", summary="获取用户ID", response_model=ReturnNoneDataModel)
async def get_user_id(authorization: Optional[str] = Header(None)):
    try:
        user_id = await get_id_by_token(authorization)  # 使用函数获取用户ID
        return ReturnNoneDataModel(code=STATUS_CODE["success"], message=f"{user_id}", success=True)
    except HTTPException as e:
        return ReturnNoneDataModel(code=STATUS_CODE["error"], message=f"{e}", success=False)
